<?php defined('SYSPATH') or die('No direct script access.');

class Controller_User extends Controller_App
{
	
	public $secure_actions = array(
		'change_password' => 'login',
		'account' => 'login',
	);
	
	public function after() {
		
		$user_styles = array(
			URL::base() . 'media/user/default.css' => 'screen',
			URL::base() . 'media/site/css/default.css' => 'screen',	
		);
		
		$this->template->styles = array_merge($this->template->styles, $user_styles);
		parent::after();
	}
	
	public function action_login() {
		
		if(Auth::instance()->logged_in() != 0) {
			$this->request->redirect("site/index");
		}
		
		if($_POST){
			if(isset($_POST['remember_me'])){
				$_POST['remember_me'] = 1;
			}else{
				$_POST['remember_me'] = 0;
			}
		}
		
		$post = Validation::factory($_POST);
		$post
			->rule('username', 'not_empty')
			->rule('password', 'not_empty')
			->rule('username', 'min_length', array(':value', 4))
			->rule('password', 'min_length', array(':value', 6))
			->rule('remember_me', 'range', array(':value', 0, 1));
		
		
		if($post->check()) {
			if(Auth::instance()->logged_in() != 0) {
				$this->request->redirect('site/index');
			}else{
				$status = Auth::instance()->login($post['username'], $post['password'], $post['remember_me'] == 1);
				if($status){
					if(isset($_GET["purl"])) {
						$this->request->redirect($_GET["purl"]);
					}
					$this->request->redirect('site/index');
				}else{
					$login_fail = true;
				}
			}
		}
		
		if($_POST){
			$errors = $post->errors();
			if(isset($errors['username'])){
				$errors['username'] = "Usuario inválido";
			}
			if(isset($errors['password'])){
				$errors['password'] = "Contraseña inválida";
			}
			if(isset($login_fail)){
				$errors['general'] = "Datos inválidos";
			}
		}else{
			$errors = NULL;
		}	
		
		$title = 'Iniciar Sesión';
		$fields = array(
			Form::label('username', 'Usuario o Email' ) => Form::input('username', isset($post['username']) ? $post['username'] : "", array('size' => 25, 'maxlength' => 127)),
			Form::label('password', 'Contraseña') => Form::password('password', NULL, array('size' => 25, 'maxlength' => 45)),
			Form::label('remember_me', 'No cerrar sesión') => Form::checkbox('remember_me', 1, isset($post['remember_me']) ? $post['remember_me'] == 1 : false ),
			NULL => Form::submit(NULL, 'Iniciar Sesión'),
		);
		$form_open = Form::open('user/login', array('method' => 'POST'));
		
		$top_content = '<div>No tenés cuenta? <a href="' . URL::site('user/register') . '">Crear una cuenta</a></div>';
		$bottom_content = "No te acordás tu contraseña? <a href=\"" . URL::site("user/password_assistance") . "\">Recuperar contraseña</a>";
		$this->userForm($title, $form_open, $fields, $errors, $top_content, $bottom_content);
	}

	public function action_register() {
		
		if(Auth::instance()->logged_in() != 0) {
			$this->request->redirect("site/index");
		}
		
		$user = Model::factory('user');
		
		$post = Validation::factory($_POST);
		$post
			->rule('username', 'not_empty')
			->rule('email', 'not_empty')
			->rule('password', 'not_empty')
			->rule('username', 'min_length', array(':value', 4))
			->rule('username', 'max_length', array(':value', 32))
			->rule('email', 'email')
			->rule('password', 'min_length', array(':value', 6))
			->rule('password', 'max_length', array(':value', 32))
			->rule('confirm_password', 'min_length', array(':value', 6))
			->rule('confirm_password', 'max_length', array(':value', 32))
			->rule('confirm_password', 'matches', array(':validation', 'confirm_password', 'password'))
			->rule('username', array($user, 'username_available'), array(':validation', 'username'))
			->rule('email', array($user, 'email_available'), array(':validation', 'email'));
		
		if($post->check()) {
			$user = ORM::factory('user');
			$user->username = $post['username'];
			$user->email = $post['email'];
			$user->password = $post['password'];
			$user->save();
			$login_role = new Model_Role(array('name' => 'login'));
			$user->add('roles', $login_role);
			
			Auth::instance()->login($post['username'], $post['password']);
			$this->request->redirect('site/index');
		}
		
		if($_POST) {
			$errors = $post->errors();
			if(isset($errors['username'])) {
				$errors['username'] = "Nombre de usuario inválido.";
			}
			if(isset($errors['email'])) {
				$errors['email'] = "Email inválido.";
			}
			if(isset($errors['password'])) {
				$errors['password'] = "Contraseña inválida.";
			}
			if(isset($errors['confirm_password'])) {
				$errors['confirm_password'] = "Confirmación de contraseña inválida.";
			}
		}else{
			$errors = NULL;
		}
		
		
		$title = "Crear cuenta";
		$form_open = Form::open('user/register', array('method' => 'POST'));
		$top_content = '<div>Ya tenés cuenta? <a href="' . URL::site('user/login') . '">Iniciar sesión</a></div>';
		$fields = array(
			Form::label('username', 'Usuario') => Form::input('username', isset($post['username']) ? $post['username'] : "", array('size' => 25, 'maxlenght' => 32, 'autocomplete' => 'off')),
			Form::label('email', 'Email') => Form::input('email', isset($post['email']) ? $post['email'] : "", array('size' => 25, 'maxlenght' => 127, 'autocomplete' => 'off')),
			Form::label('password', 'Contraseña') => Form::password('password', NULL, array('size' => 25, 'maxlength' => 32)),
			Form::label('confirm_password', 'Confirmar contraseña') => Form::password('confirm_password', NULL, array('size' => 25, 'maxlength' => 32)),
			" " => "<div class=\"terms_and_conditions\">Al hacer clic en \"Crear mi cuenta\" certifica que ha leído y acepta los <a href=\"#\">Terminos y Condiciones del Servicio</a>.</div>",
			NULL => Form::submit(NULL, 'Crear mi cuenta'),
		);
		$this->userForm($title, $form_open, $fields, $errors, $top_content);
	}

	public function userForm($title, $form_open, $fields, $errors = NULL, $top_content = NULL, $bottom_content = NULL) {
		$this->template->title = $title;	
		$this->template->content = new View("user/form");
		$this->template->content->title = $title;
		$this->template->content->form_open = $form_open;
		$this->template->content->fields = $fields;
		$this->template->content->errors = $errors;
		$this->template->content->top_content = $top_content;
		$this->template->content->bottom_content = $bottom_content;
	}

	public function action_noaccess() {
		$this->messageView();
		$this->template->styles = array(URL::base() . 'media/app/default.css' => 'screen');
		$this->template->title = "Acceso denegado";
		$this->template->content->message = "No tiene acceso al sitio solicitado.";
	}
	
	public function action_terms_and_conditions() {
		$this->template->styles = array(URL::base() . 'media/app/default.css' => 'screen');
		$this->template->title = "Terminos y Condiciones";
		$this->template->content = new View('user/termsAndConditions');
	}
	
	public function action_logout() {
		if(isset($_GET["tk"])) {
			if(Security::check($_GET["tk"])) {
				Auth::instance()->logout();
			}
		}
		$this->request->redirect('site/index');
	}
	
	private function headerAndFooterView() {
		$this->template->content = new View("site/default");
		$this->template->content->header = new View("site/header");
		$this->template->content->footer = new View("site/footer");
		$this->template->content->content = "";
	}
	
	public function action_account() {
		
		$provinces = Model::factory('province')->find_all();
		$array_provinces = array();
		$array_provinces[0] = "";
		$user = Auth::instance()->get_user();
		
		foreach($provinces as $province) {
			$array_provinces[$province->id] = $province->name;
		}
		
		if(isset($_POST["form"])) {
			if(strcmp($_POST["form"], "userdata_form") == 0){
				if(!Auth::instance()->check_password($_POST["current_password"])) {
					$userdata_errors = "Contraseña actual inválida";		
				}
				$post = Validation::factory($_POST);
				$post
					->rule('password', 'not_empty')
					->rule('password', 'min_length', array(':value', 6))
					->rule('confirm_password', 'matches', array(':validation', 'confirm_password', 'password'));
				if(!isset($userdata_errors) && $post->check()) {
					$user->password = $post["password"];
					$user->save();
					$userdata_success = "La contraseña ha sido cambiada satisfactoriamente.";
				}else{
					$errors = $post->errors();
					if(isset($errors["current_password"])) {
						$userdata_errors = "Contraseña actual inválida.";
					}else if(isset($errors["password"])){
						$userdata_errors = "Nueva contraseña inválida.";
					}else if(isset($errors["confirm_password"])){
						$userdata_errors = "Las contraseñas no coinciden.";
					}
				}
			}else if(strcmp($_POST["form"], "personaldata_form") == 0) {
				$post = Validation::factory($_POST);
				$post
					->rule('name', 'max_length', array(':value', 60))
					->rule('lastname', 'max_length', array(':value', 60))
					->rule('location', 'max_length', array(':value', 100))
					->rule('province', 'range', array(':value', 0, 23));
					
				if($post->check()) {
					$userinfo = ORM::factory('userinformation', $user->id);
					if(!$userinfo->loaded()) {
						$userinfo->user_id = $user->id;
					}
					$userinfo->name = $post["name"];
					$userinfo->lastname = $post["lastname"];
					$userinfo->location = $post["location"];
					$userinfo->province_id = $post["province"];
					$userinfo->country_id = 1;
					$userinfo->save();
					$personaldata_success = "Los datos han sido actualizados satisfactoriamente.";
				}else{
					$personaldata_errors = "Los datos ingresados presentaron errores en la actualización.";
				}
			}
		}
		$this->template->title = "Mi cuenta";
		$this->headerAndFooterView();
		
		$userinfo = ORM::factory('userinformation', $user->id);
		
		$form = $this->template->content->content = new View('user/editInformation');
		$form->provinces = $array_provinces;
		$form->userdata_success = isset($userdata_success) ? $userdata_success : NULL;
		$form->userdata_errors = isset($userdata_errors) ? $userdata_errors : NULL;
		$form->personaldata_errors = isset($personaldata_errors) ? $personaldata_errors : NULL;
		$form->personaldata_success = isset($personaldata_success) ? $personaldata_success : NULL;
		if($userinfo->loaded()) {
			$form->userinfo = $userinfo;
		}else{
			$form->userinfo = NULL;	
		}
		$form->user = $user;
		$this->template->styles = array(
			URL::base() . 'media/user/css/default.css' => 'screen',
			URL::base() . 'media/site/css/default.css' => 'screen'
		);
	}
	
	private function sendRecoveryEmail($email, $token) {
		$content = new View("user/recover_password");
		$content->email = $email;
		$content->token = $token;
		mail($email, "Subteteca | Restablecer contraseña.", $content->render());
	}
		
	
	public function action_password_assistance() {
		$captcha = Captcha::instance();
		
		$post = Validation::factory($_POST);
		$post
			->rule('email', 'not_empty')
			->rule('email', 'email')
			->rule('captcha', 'not_empty')
			->rule('captcha', 'exact_length', array(':value', 4));
		
		if($post->check() && Captcha::valid($post["captcha"])) {
			$user = Model::factory("user")->where("email", "=", $post["email"])->find();
			if($user->loaded()) {
				$upa = ORM::factory("userpa", $user->id);
				if(!$upa->loaded()){
					$upa->user_id = $user->id;
				}
				$upa->token = sha1($user->id . $user->email . $user->username . rand(1,10000));
				$upa->save();
				$form = $this->template->content = new View("user/form");
				$form->title = $this->template->title = "Recuperar contraseña";
				$form->form_open = Form::open("site/index");
				$this->sendRecoveryEmail($user->email, $upa->token);
				$form->fields = array(
				"" => "Hemos enviado un email a su cuenta, para reestablecer su contraseña.",
				" " => "<a href=\"" . URL::site("site/index") . "\">Volver al sitio</a>",
				);
				return;
			}else{
				$errors["general"] = $post["email"] . " aún no es usuario de Subteteca.";
			}
		}
		
		$form = $this->template->content = new View("user/form");
		$form->title = $this->template->title = "Recuperar contraseña";
		$form->form_open = Form::open("user/password_assistance");
		$form->errors = isset($errors) ? $errors : NULL;
		$form->fields = array(
			Form::label('email', 'Ingrese su email') => Form::input('email'),
			" " => $captcha->render(),
			Form::label('captcha', 'Letras') => Form::input('captcha', NULL, array("size" => 6, "maxlength" => 4)),
			NULL => Form::submit(NULL, 'Enviar'),
		);
		
	}

	public function action_password_recover() {
		if(isset($_GET["em"]) && isset($_GET["tk"])) {
			$user = ORM::factory("user")->where("email", "=", $_GET["em"])->find();
			if($user->loaded()) {
				$upa = ORM::factory("userpa", $user->id);
				$diff = date("YmdHi", strtotime($upa->created_at)) - date("YmdHi", time());
				if($upa->token == $_GET["tk"] && $diff < (24 * 60)) {
					Auth::instance()->force_login($user);
					$upa->delete();
					$this->request->redirect("user/account");
				}else{
					$message = "Token inválido";	
				}
			}
			$this->messageView();
			$this->template->title = "Link inválido";
			$this->template->content->message = isset($message) ? $message : "Usuario inválido";
			$this->template->styles = array(
				URL::base() . "media/app/default.css" => "screen",
			);
		}
	}
		
}